package com.ossjk.qlh.minapp.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ossjk.config.wxminiapp.WxMaConfiguration;
import com.ossjk.core.base.controller.BaseController;
import com.ossjk.core.constant.Constant;
import com.ossjk.core.util.CommonUtil;
import com.ossjk.core.util.JwtTokenUtil;
import com.ossjk.core.vo.RequestBean;
import com.ossjk.core.vo.ResponseBean;
import com.ossjk.qlh.minapp.entity.Enterprise;
import com.ossjk.qlh.minapp.entity.Member;
import com.ossjk.qlh.minapp.service.IEnterpriseService;
import com.ossjk.qlh.minapp.service.IMemberService;
import com.ossjk.qlh.minapp.vo.MemberVo;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api")
public class IndexController extends BaseController {
    @Autowired
    private WxMaConfiguration wxMaConfiguration;
    @Autowired
    private IMemberService iMemberService;
    @Autowired
    private IEnterpriseService iEnterpriseService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 微信登陆
     */
    @PostMapping("/wxLogin")
    public ResponseBean wxLogin(@RequestBody RequestBean requestBean) throws WxErrorException {
        String code = (String) requestBean.getParam().get("code");
        if (CommonUtil.isBlank(code)) {
            return responseException("param.code不能为空");
        }
        WxMaService wxMaService = wxMaConfiguration.getMaService();
        WxMaJscode2SessionResult result = wxMaService.getUserService().getSessionInfo(code);
        return responseSuccess(result);
    }

    @PostMapping("/getWxUserInfo")
    public ResponseBean getWxUserInfo(@RequestBody RequestBean requestBean) throws WxErrorException {

        WxMaService wxMaService = wxMaConfiguration.getMaService();
        String sessionKey = (String) requestBean.getParam().get("sessionKey");
        if (CommonUtil.isBlank(sessionKey)) {
            return responseException("param.sessionKey不能为空");
        }
        String signature = (String) requestBean.getParam().get("signature");
        if (CommonUtil.isBlank(signature)) {
            return responseException("param.signature不能为空");
        }
        String rawData = (String) requestBean.getParam().get("rawData");
        if (CommonUtil.isBlank(rawData)) {
            return responseException("param.rawData不能为空");
        }
        String encryptedData = (String) requestBean.getParam().get("encryptedData");
        if (CommonUtil.isBlank(encryptedData)) {
            return responseException("param.encryptedData不能为空");
        }
        String iv = (String) requestBean.getParam().get("iv");
        if (CommonUtil.isBlank(iv)) {
            return responseException("param.iv不能为空");
        }
        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            log.debug("校验失败");
            return responseFail("用户信息校验失败");
        }

        // 解密用户信息
        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        return responseSuccess(userInfo);
    }

    @PostMapping("/getWxPhoneInfo")
    public ResponseBean getWxPhoneInfo(@RequestBody RequestBean requestBean) throws WxErrorException {
        WxMaService wxMaService = wxMaConfiguration.getMaService();
        String sessionKey = (String) requestBean.getParam().get("sessionKey");
        if (CommonUtil.isBlank(sessionKey)) {
            return responseException("param.sessionKey不能为空");
        }
        String signature = (String) requestBean.getParam().get("signature");
        if (CommonUtil.isBlank(signature)) {
            return responseException("param.signature不能为空");
        }
        String rawData = (String) requestBean.getParam().get("rawData");
        if (CommonUtil.isBlank(rawData)) {
            return responseException("param.rawData不能为空");
        }
        String encryptedData = (String) requestBean.getParam().get("encryptedData");
        if (CommonUtil.isBlank(encryptedData)) {
            return responseException("param.encryptedData不能为空");
        }
        String iv = (String) requestBean.getParam().get("iv");
        if (CommonUtil.isBlank(iv)) {
            return responseException("param.iv不能为空");
        }
        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            log.debug("校验失败");
            return responseFail("用户信息校验失败");
        }

        // 解密微信手机号
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
        return responseSuccess(phoneNoInfo);
    }


    @PostMapping("/register")
    public ResponseBean register(@RequestBody RequestBean<MemberVo> requestBean) {
        //获取注册的会员信息
        MemberVo memberVo = requestBean.getData();

        if (CommonUtil.isBlank(memberVo)) {
            return responseException("格式错误");
        }
        if (CommonUtil.isBlank(memberVo.getName())) {
            return responseException("昵称不能为空");
        }
        if (CommonUtil.isBlank(memberVo.getPhone())) {
            return responseException("手机不能为空");
        }
        if (CommonUtil.isBlank(memberVo.getPic())) {
            return responseException("头像不能为空");
        }
        if (CommonUtil.isBlank(memberVo.getCode())) {
            return responseException("团购码不能为空");
        }
        if (CommonUtil.isBlank(memberVo.getWxid())) {
            return responseException("openid不能为空");
        }
        //判断openid是否存在
        Member tmpMember = iMemberService.getOne(new QueryWrapper<Member>().eq("wxid", memberVo.getWxid()));
        if (!CommonUtil.isBlank(tmpMember)) {
            return responseFail("openid已经注册");
        }

        //判断团购码不能为空是否存在
        Enterprise tmpEnterprise = iEnterpriseService.getOne(new QueryWrapper<Enterprise>().eq("code", memberVo.getCode()));
        if (CommonUtil.isBlank(tmpEnterprise)) {
            return responseFail("团购码不存在");
        }

        memberVo.setRname(memberVo.getName());
        //设置成员企业id
        memberVo.setEid(tmpEnterprise.getId());
        //状态1.待确认，2，已确认，3，离职，4，团长
        memberVo.setState(1);
        if (iMemberService.save(memberVo)) {
            return responseSuccess();
        } else {
            return responseFail();
        }
    }

    @PostMapping("/login")
    public ResponseBean login(@RequestBody RequestBean requestBean) {
        String wxid = (String) requestBean.getParam().get("wxid");
        if (CommonUtil.isBlank(wxid)) {
            return responseException("openid不能为空");
        }
        //根据openid查找成员
        Member member = iMemberService.getOne(new QueryWrapper<Member>().eq("wxid", wxid));

        if (CommonUtil.isBlank(member)) {
            return responseFail("成员不存在");
        }
        //登录成功
        //分发token
        String tokenStr = jwtTokenUtil.generalToken(member.getId(), member.getName());
        //设置token
        redisTemplate.boundValueOps(Constant.REQUEST_HEADER_TOKEN + member.getId()).set(tokenStr, jwtTokenUtil.getDuration(), TimeUnit.MILLISECONDS);
        return responseSuccess(tokenStr);
    }

    @PostMapping("/getInfo")
    public ResponseBean getInfo(@RequestBody RequestBean requestBean) {
        System.out.println("6666测试通过");
        return responseSuccess();
    }
}
